<template>
    <div class="left_menu">
        <div class="language-switch">
            <span @click="switchLanguage('zh')" :class="{'current': $i18n.locale === 'zhCN'}">{{ $t('common.chinese') }}</span>
            <span @click="switchLanguage('en')" :class="{'current': $i18n.locale === 'en'}">{{ $t('common.english') }}</span>
        </div>
        <h1 class="menu_title">{{ $t('pageTitle.adminSystem') }}</h1>
        <div class="user_info">
            <div class="photo" @click="logout"></div>
            <div class="user_name">{{ user.username }}</div>
            <el-button @click="verifyPwd" size="mini" class="verifyPwd" type="text">{{ $t('common.changePassword') }}</el-button>
        </div>

        <!--修改密码弹窗-->
        <el-dialog :title="$t('common.changePassword')" :visible.sync="dialogFormVisible" :width="'416px'" :center="false">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-position="top">
                <el-form-item :label="$t('common.plsInputOldPassword')" prop="oldPassword"><!--请输入旧密码-->
                    <el-input v-model="ruleForm.oldPassword" auto-complete="off" type="password"></el-input>
                </el-form-item>
                <el-form-item :label="$t('common.plsInputNewPassword')" prop="newPassword"><!--请输入新密码-->
                    <el-input v-model="ruleForm.newPassword" auto-complete="off" type="password"></el-input>
                </el-form-item>
                <el-form-item :label="$t('common.confirmNewPassword')" prop="confirmPassword"><!--确认新密码-->
                    <el-input v-model="ruleForm.confirmPassword" auto-complete="off" type="password"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="modify_dialog_footer">
                <el-button class="save_btn" type="primary" @click="submitForm('ruleForm')"  :disabled="!ruleForm.oldPassword || !ruleForm.newPassword || !ruleForm.confirmPassword">{{ $t('common.submit') }}</el-button>
                <el-button class="cancel_btn" @click="close">{{ $t('common.cancel') }}</el-button>
            </div>
        </el-dialog>

        <!--菜单start-->
        <div class="menu_panel">
            <ul class="menu">
                <li v-for="(menuFirst,index1) in showMenuList" :key="index1">
                    <!--一级菜单-->
                    <a @click.stop.prevent="goTo(menuFirst)" :class="{'active': menuFirst.url === $route.path || (menuFirst.urls && menuFirst.urls.indexOf($route.path) > -1)}" class="menu_icon menu_icon_user" href="javascript:void(0);">{{ menuFirst.name }} <i v-if="menuFirst.submenu && menuFirst.submenu.length" :class="{'rotate': menuFirst.collapse}" class="menu_icon_arrow el-icon-caret-bottom"></i></a>
                    <ul v-if="menuFirst.submenu && menuFirst.submenu.length && menuFirst.collapse" class="submenu">
                        <li v-for="(menuSecond,index2) in menuFirst.submenu" :key="index1+''+index2">
                            <!--二级菜单-->
                            <a @click.stop.prevent="goTo(menuSecond)" :class="{'active': menuSecond.url === $route.path || (menuSecond.urls && menuSecond.urls.indexOf($route.path) > -1)}" class="menu_icon menu_icon_user" href="javascript:void(0);">{{ menuSecond.name }} <i v-if="menuSecond.submenu && menuSecond.submenu.length" :class="{'rotate': menuSecond.collapse}" class="menu_icon_arrow el-icon-caret-bottom"></i></a>
                            <ul v-if="menuSecond.submenu && menuSecond.submenu.length && menuSecond.collapse" class="submenu">
                                <!--三级菜单-->
                                <li v-for="(menuThird,index3) in menuSecond.submenu" :key="index1+''+index2+''+index3">
                                    <a @click.stop.prevent="goTo(menuThird)" :class="{'active': menuThird.url === $route.path || (menuThird.urls && menuThird.urls.indexOf($route.path) > -1)}" class="menu_icon menu_icon_user" href="javascript:void(0);">{{ menuThird.name }}<i v-if="menuThird.submenu && menuThird.submenu.length" :class="{'rotate': menuThird.collapse}" class="menu_icon_arrow el-icon-caret-bottom"></i></a>
                                    <!--四级菜单-->
                                    <ul v-if="menuThird.submenu && menuThird.submenu.length && menuThird.collapse" class="submenu">
                                        <li v-for="(menuFourth,index4) in menuThird.submenu" :key="index1+''+index2+''+index3+''+index4">
                                            <a @click.stop.prevent="goTo(menuFourth)" :class="{'active': menuFourth.url === $route.path}" class="menu_icon menu_icon_user" href="javascript:void(0);">{{ menuFourth.name }}</a>
                                        </li>
                                    </ul>
                                    <!--四级菜单END-->
                                </li>
                            </ul><!--三级菜单end-->
                        </li>
                    </ul><!--二级菜单end-->
                </li>
            </ul><!--一级菜单end-->
        </div>
        <!--菜单end-->
    </div>
</template>

<script>
    import eventBus from '@/libs/event-bus';
    import { eventConf } from '@/config';
    import auth from '@/service/auth';
    import regExp from '@/config/regExp';
    import menuData from '@/config/menu';
    import md5 from 'blueimp-md5';

    export default {
        name: 'leftMenu',
        data() {
            return {
                jumpToUrl: '',
                user: this.$storage.get('user') || {},
                dialogFormVisible: false,
                ruleForm: {
                    oldPassword: '',
                    newPassword: '',
                    confirmPassword: '',
                },
                showMenuList: [],
                cacheResourceMap: {},
            };
        },
        computed: {
            active() {
                return this.$route.path;
            },
            rules() {
                const validatenewPass = (rule, value, callback) => {
                    if (value === '') {
                        callback(new Error(this.$tc('common.plsInputNewPassword')));// 请输入新密码
                    } else {
                        if (this.ruleForm.newPassword.length < 6 || this.ruleForm.newPassword.length > 10) {
                            callback(new Error(this.$tc('common.plsInput6To10Password')));// 请输入6-10位数字字母组合密码
                        } else if (!regExp.pwd.test(value)) {
                            callback(new Error(this.$tc('common.plsInput6To10Password')));// 请输入6-10位数字字母组合密码
                        }
                        callback();
                    }
                };
                const checkpass = (rule, value, callback) => {
                    if (value === '') {
                        callback(new Error(this.$tc('common.confirmNewPassword')));// 确认新密码
                    } else if (value !== this.ruleForm.newPassword) {
                        callback(new Error(this.$tc('common.newPasswordNotSame')));// 新密码输入不一致
                    } else {
                        callback();
                    }
                };
                const rules = {
                    oldPassword: [
                        { required: true, message: this.$t('common.plsInputOldPassword'), trigger: 'blur' }// 请输入旧密码
                    ],
                    newPassword: [
                        { required: true, validator: validatenewPass, trigger: 'blur' }
                    ],
                    confirmPassword: [
                        { required: true, validator: checkpass, trigger: 'blur' }
                    ]
                };
                return rules;
            }
        },
        methods: {
            logout() {
                auth.logout(() => {
                    this.$message.success('Logout');
                    this.$router.replace('/login')
                });
                //storage.removeAll();
                sessionStorage.clear();
            },
            eventListening() {
                eventBus.$on(eventConf.ELOGIN, () => {
                    this.user = this.$storage.get('user');
                    this.redirectTo();
                });
                eventBus.$on(eventConf.ELOGOUT, () => {
                    this.user = null;
                });
            },
            redirectTo() {
                const redirectUrl = this.$route.query.redirectUrl || this.jumpToUrl;

                this.$router.push({ path: redirectUrl });
            },
            getResourceList() {
                if (!this.user || !this.user.token) return;
                // 获取菜单
                this.$api.systemManage.getResourceList({ type: 'MENU' }).then((res) => {
                    const {  data } = res;
                    if (data && data.resourceList && data.resourceList.length > 0) {
                        data.resourceList.forEach(menu => {
                            this.cacheResourceMap[menu.path] = menu;
                        });
                        this.filterMenu(menuData.menu);
                        this.showMenuList = [];
                        this.filterShowMenu(this.showMenuList, menuData.menu);
                    }
                });
            },
            filterMenu(menuList) {
                // 根据后台返回判断是否显示该菜单
                let urlList = new Set();
                menuList.forEach((menu) => {
                    // 是否显示该菜单
                    if (this.cacheResourceMap[menu.path]) {
                        menu.show = true;
                    }
                    if (menu.submenu) {
                        const s = this.filterMenu(menu.submenu);
                        menu.urls = [...s];
                        urlList = new Set([...urlList, ...s]);
                    } else if (menu.url){
                        urlList.add(menu.url);
                    }
                });
                return urlList;
            },
            filterShowMenu(showMenu, menuList) {
                // 判断哪些菜单可以显示，组成显示菜单
                menuList.forEach((menu) => {
                    if (menu.show && !menu.noShow) {
                        if (menu.submenu) {
                            const menuTemp = Object.assign({}, menu);
                            menuTemp.submenu = [];
                            menuTemp.collapse = false;
                            this.filterShowMenu(menuTemp.submenu, menu.submenu);
                            showMenu.push(menuTemp);

                            if (menuTemp.urls.indexOf(this.$route.path) > -1) {
                                menuTemp.collapse = true;
                            }
                        } else {
                            if (menu.url && '' === this.jumpToUrl) {
                                this.jumpToUrl = menu.url;
                            }
                            showMenu.push(menu);
                        }
                    }
                });
            },
            goTo(menu) {
                if (menu.submenu) {
                    menu.collapse = !menu.collapse;
                }
                if (menu.url) {
                    // this.$store.state.menu.show = false;
                    this.$router.push({ path: menu.url });
                }
            },
            // 修改密码
            verifyPwd(){
                this.dialogFormVisible = true;
            },
            submitForm() {
                const { oldPassword, newPassword, confirmPassword } = this.ruleForm;
                const params = {
                    userId: this.user.userId,
                    oldPassword: md5(oldPassword),
                    newPassword: md5(newPassword),
                    confirmPassword: md5(confirmPassword)
                };
                this.$api.user.resetPwd(params).then((response) => {
                    const { status, error, msg } = response;
                    if (status === '1' && error === '00000000') {
                        this.$message.success(this.$tc('common.successfulOperation'));
                        this.close();
                    } else {
                        this.$message.error(msg);
                    }
                });
            },
            reset() {
                const { ruleForm } = this.$refs;
                if (ruleForm) {
                    ruleForm.resetFields();
                }
            },
            close(){
                this.reset();
                this.dialogFormVisible = false;
            },
            switchLanguage(language) {
                this.$storage.setLocal('language',language);
                setTimeout( () => {
                    window.location.reload()
                },100)
            }
        },
        created() {
            this.getResourceList();
            this.eventListening();
        }
    }
</script>

<style lang="scss" scoped>
    @import '~@/assets/scss/function';
    .menu_panel{
        /*display: flex;*/
        /*flex-direction: column;*/
        /*flex: 1;*/
        /*height: 100%;*/
    }
    .menu_icon{
        background-repeat: no-repeat;
        background-size: 20px 20px;
        background-position: 38px center;
    }
    .menu{
        a{
            display: block;
            padding: 0 16px 0 10px;
            font-weight:bold;
            color: #47c5b2;
            font-size: 14px;
            height: 56px;
            line-height: 56px;
            opacity: 1;
            overflow: hidden;
            text-overflow:ellipsis;
            &:hover, &.active{
                opacity: 1;
                background-color: rgba(0, 0, 0, 0.1);
            }
            i{
                float: right;
                height: 56px;
                line-height: 56px;
            }
            .menu_icon_arrow.rotate{
                transform: rotate(180deg);
            }
        }
        .submenu{// 二级菜单
            a{
                background-color: rgba(0, 0, 0, 0.1);
                padding-left: 20px;
                font-weight:normal;
                opacity: 0.8;
                overflow: hidden;
                text-overflow:ellipsis;
                &.active{
                    background-color: rgba(0, 0, 0, 0.4);
                }
            }
            .menu_icon{
                background-position: 54px center;
            }
            .submenu{// 三级菜单
                a{
                    padding-left: 30px;
                    background-color: rgba(0, 0, 0, 0.2);
                    opacity: 0.6;
                    overflow: hidden;
                    text-overflow:ellipsis;
                    &.active{
                        background-color: rgba(0, 0, 0, 0.5);
                    }
                }
                .menu_icon{
                    background-position: 74px center;
                }
                .submenu { // 四级菜单
                    a{
                        padding-left: 130px;
                        background-color: rgba(0, 0, 0, 0.3);
                        &.active{
                            background-color: rgba(0, 0, 0, 0.4);
                        }
                    }
                    .menu_icon{
                        background-position: 94px center;
                    }
                }
            }
        }
    }
    .left_menu{
        width: 220px;
        background: #393f3e;
        color: $primary;
        flex-shrink: 0;
        overflow: auto;
    }
    .verifyPwd {
        margin-top: 10px;
        color: #47c5b2;
    }
    .language{
        color: #b4bcbb;
        font-size: 12px;
        line-height: 16px;
        background: url("~@/assets/img/language.png") no-repeat left center;
        padding-left: 20px;
        margin: 10px 20px;
    }
    .menu_title{
        font-size: 20px;
        text-align: center;
        color: $primary;
        line-height: 1.5em;
    }
    .user_info{
        text-align: center;
        margin: 20px 0 25px;
    }
    .photo{
        display: inline-block;
        height: 48px;
        width: 48px;
        background-image: url("~@/assets/img/menu_logout.png");
        background-repeat: no-repeat;
        background-position: center;
        background-size: 48px;
        border-radius: 50%;
        cursor: pointer;
        &:hover{
            background-image: url("~@/assets/img/menu_logout.png");
        }
    }
    .menu_item{
        display: block;
        color: $primary;
        padding: 14px 0 14px 54px;
        &.router-link-active{
            color: #fff;
            background-color: $primary;
        }
        &:hover{
            color: #fff;
            background-color: tint($primary, 20);
        }
        background-repeat: no-repeat;
        background-position: 20px center;
        background-size: 24px;
    }
    .menu_icon_project{
        background-image: url("~@/assets/img/menu_icon_project.png");
        &:hover, &.router-link-active{
            background-image: url("~@/assets/img/menu_icon_project_hover.png");
        }
    }
    .menu_icon_field{
        background-image: url("~@/assets/img/menu_icon_field.png");
        &:hover, &.router-link-active{
            background-image: url("~@/assets/img/menu_icon_field_hover.png");
        }
    }
    .menu_icon_components{
        background-image: url("~@/assets/img/menu_icon_components.png");
        &:hover, &.router-link-active{
            background-image: url("~@/assets/img/menu_icon_components_hover.png");
        }
    }
    .menu_icon_release{
        background-image: url("~@/assets/img/menu_icon_release.png");
        &:hover, &.router-link-active{
            background-image: url("~@/assets/img/menu_icon_release_hover.png");
        }
    }
    .menu_icon_version{
        background-image: url("~@/assets/img/menu_icon_version.png");
        &:hover, &.router-link-active{
            background-image: url("~@/assets/img/menu_icon_version_hover.png");
        }
    }
    .language-switch {
        padding:10px 30px;
        display: flex;
        align-items: center;
        justify-content: space-around;
        span {
            cursor: pointer;
        }
        .current {
            color: #fff;
        }
    }
    .user_name {
        overflow: hidden;
        text-overflow:ellipsis;
        white-space: nowrap;
        padding:0 10px;
    }
</style>
